package tjs.study.notes.elasticsearch.insert;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import tjs.study.notes.elasticsearch.ElasticsearchApplication;
import tjs.study.notes.elasticsearch.model.Student;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by Nicky.Tang on 2022/10/31 上午11:37
 *
 * @since 02.12.10
 */
@SpringBootTest
public class Insert {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Test
    public void addBatch() throws IOException {
        for (int j = 0; j < 10; j++) {
            System.out.println("第" + j + "批次");
            List<DocWriteRequest<?>> params = new ArrayList<>();
            for (int i = 0; i < 100; i++) {
                Student student = new Student();
                student.setId(UUID.randomUUID().toString());
                student.setStudentName("name" + i + UUID.randomUUID().toString());
                IndexRequest request = new IndexRequest(ElasticsearchApplication.INDEX_NAME, "_doc", student.getId());
                request.source(JSON.toJSONString(student), XContentType.JSON);
                params.add(request);
            }

            BulkRequest bulkRequest = new BulkRequest();
            bulkRequest.add(params);
            try {
                restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            }catch (Exception ex){
                
            }
        }
    }
}
